import { ref, shallowRef, onMounted, onActivated } from 'vue';

const defaultRequestConfig = {
  // successCode: '0',
  // verify: (response, config) => {
  //   const responseCode = response.code;
  //   if (Array.isArray(config.successCode)) {
  //     return config.successCode.includes(responseCode);
  //   }
  //   return responseCode == config.successCode;
  // },
  verify: () => true,
  format: (response) => response,
};

const onMessage = (type, msg) => {
  if (!msg) return;
  // message[type](msg);
};

function useApi(api, config) {
  const reqConfig = Object.assign({}, defaultRequestConfig, config);

  const defaultParams = ref(reqConfig.defaultParams); // 每次请求都会携带的参数
  const params = ref({}); // 记录请求之后传递了的参数
  const data = shallowRef(reqConfig.initialData);
  const loading = ref(false);

  const run = async (payload) => {
    if (loading.value) return;
    loading.value = true;
    let response = null;
    let formatedData = null;
    let currentParams = null;
    try {
      // 请求参数 = 默认参数 + 传递参数
      const margeParams = { ...defaultParams.value, ...payload };
      params.value = reqConfig.searchFormat?.(margeParams) || margeParams;
      currentParams = { ...params.value };
      response = await api(currentParams);

      const pass = reqConfig.verify(response, reqConfig);

      const msg = reqConfig.message?.(pass, response);

      // console.log(response, pass, msg);

      if (pass) {
        onMessage('success', msg);
        formatedData = reqConfig.format?.(response, currentParams);
        data.value = formatedData;
        reqConfig.onPass?.(formatedData, currentParams);
      } else {
        onMessage('warnning', msg);
        reqConfig.onFail?.(response, currentParams);
      }

      reqConfig.onSuccess?.(response, currentParams);
    } catch (error) {
      console.error(error, api);
      onMessage('error', '请求失败，请重试！');
      reqConfig.onError?.(error);
    }
    loading.value = false;
    reqConfig.onFinially?.(formatedData || response, currentParams);
  };

  const refresh = () => {
    // 使用保存参数进行刷新
    run(params.value);
  };

  // 手动设置数据
  const setData = (newData) => {
    data.value = newData;
  };

  // 手动设置参数
  const setParams = (newParams) => {
    defaultParams.value = { ...defaultParams.value, ...newParams };
  };

  // onMounted(() => {
  //   if (reqConfig.auto) run();
  // });

  onActivated(() => {
    if (reqConfig.auto && !data.value.total) run();
  });

  return {
    params,
    data,
    loading,
    run,
    refresh,
    setParams,
    setData,
  };
}

export default useApi;
